package dimension.starry.block.machine.industry.steamer;

import dimension.starry.StarryDimension;
import dimension.starry.block.machine.industry.IndustryMachineRegister;
import dimension.starry.block.typeInterface.MachineTileEntity;
import dimension.starry.item.ItemRegisterManager;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

/**
 * @author 150149
 */
public class SteamTileEntity extends MachineTileEntity {

    private static final Text TITLE = Text.translatable("block." + StarryDimension.MOD_ID + ".steamer_entry");

    public SteamTileEntity(BlockPos blockPos, BlockState blockState) {
        super(IndustryMachineRegister.STEAMER_ENTRY.getBlockEntityType(), blockPos, blockState, 4, TITLE, 800);
    }

    @Override
    public ScreenHandler createMenu(int sycID, PlayerInventory inventory, PlayerEntity player) {
        return new SteamerContainer(
            IndustryMachineRegister.STEAMER_ENTRY.getScreenHandlerType(), sycID, inventory, getPos());
    }

    @Override
    public void tick(World world, BlockPos pos, BlockState blockState, MachineTileEntity blockEntity) {
        if (world == null || world.isClient()) {
            return;
        }

        ItemStack waterPotItemStack = this.inventory.getStack(0);
        ItemStack fuelItemStack = this.inventory.getStack(1);

        if (waterPotItemStack.isEmpty()) {
            this.setMachineStatus(false);
            this.resetProgress();
        }

        if (waterPotItemStack.getItem().equals(ItemRegisterManager.WATER_STONE_POT.getItem())) {
            if (this.getProgress() >= this.getConsumeTime()) {
                ItemStack itemStack = new ItemStack(ItemRegisterManager.STONE_POT.getItem());
                if (this.inventory.canInsert(itemStack)) {
                    waterPotItemStack.setCount(waterPotItemStack.getCount() - 1);
                    this.resetProgress();
                    this.inventory.addStack(itemStack);
                }
            } else if (!this.consumeFuel() && !fuelItemStack.isEmpty() &&
                getFuelAddCount(fuelItemStack.getItem()) != 0) {
                fuelItemStack.setCount(fuelItemStack.getCount() - 1);
                this.addFuel(getFuelAddCount(fuelItemStack.getItem()));
                this.consumeFuel();
                this.setMachineStatus(true);
            }
        } else {
            this.setMachineStatus(false);
            this.resetProgress();
        }
    }

}
